import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response
      
      if (status === 401) {
        // token过期或无效，清除本地存储并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return Promise.reject(new Error('登录已过期，请重新登录'))
      }
      
      if (status === 403) {
        return Promise.reject(new Error(data.message || '权限不足'))
      }
      
      if (status === 404) {
        return Promise.reject(new Error(data.message || '请求的资源不存在'))
      }
      
      if (status >= 500) {
        return Promise.reject(new Error('服务器内部错误，请稍后重试'))
      }
      
      return Promise.reject(new Error(data.message || '请求失败'))
    } else if (error.request) {
      // 网络错误
      return Promise.reject(new Error('网络连接失败，请检查网络设置'))
    } else {
      // 其他错误
      return Promise.reject(new Error(error.message || '请求失败'))
    }
  }
)

// 认证相关API
export const authAPI = {
  // 用户注册
  register: (userData) => api.post('/auth/register', userData),
  
  // 用户登录
  login: (credentials) => api.post('/auth/login', credentials),
  
  // 获取当前用户信息
  getCurrentUser: () => api.get('/auth/me'),
  
  // 更新用户信息
  updateProfile: (userData) => api.put('/auth/me', userData),
  
  // 修改密码
  changePassword: (passwordData) => api.put('/auth/password', passwordData),
  
  // 退出登录
  logout: () => api.post('/auth/logout'),
  
  // 验证token
  verifyToken: () => api.get('/auth/verify')
}

// 预约相关API
export const appointmentAPI = {
  // 获取预约列表
  getList: (params = {}) => api.get('/appointments', { params }),
  
  // 获取预约详情
  getById: (id) => api.get(`/appointments/${id}`),
  
  // 创建预约
  create: (appointmentData) => api.post('/appointments', appointmentData),
  
  // 更新预约
  update: (id, appointmentData) => api.put(`/appointments/${id}`, appointmentData),
  
  // 删除预约
  delete: (id) => api.delete(`/appointments/${id}`),
  
  // 获取我创建的预约
  getMyAppointments: (params = {}) => api.get('/appointments/my/list', { params }),
  
  // 获取我参与的预约
  getParticipatedAppointments: (params = {}) => api.get('/appointments/my/participated', { params }),
  
  // 退出预约
  leaveAppointment: (id) => api.delete(`/appointments/${id}/participants/me`),
  
  // 关闭预约
  closeAppointment: (id) => api.put(`/appointments/${id}/close`)
}

// 申请相关API
export const applicationAPI = {
  // 创建申请
  create: (applicationData) => api.post('/applications', applicationData),
  
  // 获取我的申请列表
  getMyApplications: (params = {}) => api.get('/applications/my', { params }),
  
  // 获取预约的申请列表
  getAppointmentApplications: (appointmentId, params = {}) => 
    api.get(`/applications/appointment/${appointmentId}`, { params }),
  
  // 处理申请（通过或拒绝）
  processApplication: (id, processData) => api.put(`/applications/${id}/process`, processData),
  
  // 取消申请
  cancelApplication: (id) => api.put(`/applications/${id}/cancel`),
  
  // 获取申请详情
  getById: (id) => api.get(`/applications/${id}`),
  
  // 获取待处理申请数量
  getPendingCount: () => api.get('/applications/pending/count'),
  
  // 获取收到的申请列表
  getReceivedApplications: (params = {}) => api.get('/applications/received', { params })
}

// 游戏类型相关API（如果后端有的话）
export const categoryAPI = {
  // 获取游戏类型列表
  getList: () => api.get('/categories')
}

// 通知相关API
export const notificationAPI = {
  // 获取通知列表
  getNotifications: (unreadOnly = false) => api.get('/notifications', { params: { unread_only: unreadOnly } }),
  
  // 标记通知为已读
  markAsRead: (id) => api.put(`/notifications/${id}/read`),
  
  // 标记所有通知为已读
  markAllAsRead: () => api.put('/notifications/read-all'),
  
  // 获取未读通知数量
  getUnreadCount: () => api.get('/notifications/unread-count')
}

// 通用工具函数
export const apiUtils = {
  // 处理分页参数
  buildPaginationParams: (page = 1, limit = 10) => ({
    page,
    limit
  }),
  
  // 处理搜索参数
  buildSearchParams: (keyword = '', category = '', status = '') => {
    const params = {}
    if (keyword) params.keyword = keyword
    if (category) params.category_id = category
    if (status) params.status = status
    return params
  },
  
  // 格式化错误信息
  formatError: (error) => {
    if (error.response && error.response.data) {
      return error.response.data.message || '操作失败'
    }
    return error.message || '网络错误'
  }
}

export default api
